package baoycode.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.Writer;
import java.util.Map;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMakerUtils {

	public static Configuration getFreeMarkerCfg(String ftlPath) {
		Configuration freemarkerCfg = new Configuration();
		freemarkerCfg.setBooleanFormat("true,false");
		freemarkerCfg.setNumberFormat("#");
		freemarkerCfg.setDefaultEncoding("UTF-8");
		try {
			freemarkerCfg.setDirectoryForTemplateLoading(new File(ftlPath));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return freemarkerCfg;
	}

	public static Configuration getFreeMarkerCfg(Class<?> cls, String templatePath) {
		Configuration freemarkerCfg = new Configuration();
		freemarkerCfg.setBooleanFormat("true,false");
		freemarkerCfg.setDefaultEncoding("UTF-8");
		freemarkerCfg.setClassForTemplateLoading(cls, templatePath);
		return freemarkerCfg;
	}
	
	
	
	public static boolean generateFile(StringReader sr, Map<?, ?> propMap, String targetFile) {
		try {
			Configuration freemarkerCfg = new Configuration();
			freemarkerCfg.setBooleanFormat("true,false");
			freemarkerCfg.setDefaultEncoding("UTF-8");
			Template t = new Template(null, sr, freemarkerCfg); 
			File fo = new File(targetFile);
			if (!fo.exists()) {
				String path = targetFile.substring(0, targetFile.lastIndexOf(File.separator));
				File pFile = new File(path);
				pFile.mkdirs();
			}
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fo), "UTF-8"));
			t.process(propMap, out);
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public static boolean generateFile(Configuration cfg, String templateFileName, Map<?, ?> propMap, String relPath,
			String fileName) {
		try {
			Template t = cfg.getTemplate(templateFileName);

			File dir = new File(relPath);
			if (!dir.exists()) {
				dir.mkdir();
			}

			File afile = new File(relPath + File.separator + fileName);
			System.out.println("=============>>>>>>>>>>>>>>>>" +  afile.getPath());

			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(afile), "UTF-8"));

			t.process(propMap, out);
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

}
